package com.link_with_health.webSocket;

import com.link_with_health.config.ApplicationContextAwareGetBean;
import com.link_with_health.service.TalkRoomService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/videoMedia/{inquiryId}/{userId}")
@Component
@Scope("prototype")
public class VideoMediaServer {

    private final Logger logger = LoggerFactory.getLogger(VideoMediaServer.class);

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */

    private static ConcurrentHashMap<String, ConcurrentHashMap<String, Session>>
            allVideoMediaPool = new ConcurrentHashMap<>();

    /**
     * 根据inquiry id 保存聊天信息
     */
    private static ConcurrentHashMap<String, StringBuffer> historyMsg = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";
    /**
     * 接受的userId
     */
    private String inquiryId = "";


    @OnOpen
    public void onOpen(Session session
            , @PathParam("inquiryId") String inquiryId
            ,@PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        this.inquiryId = inquiryId;

        //初始化webSocket
        initWebSocket();

        logger.info("[videoMediaServer 开始连接------]");
    }

    /**
     *
     * @param message 传输的信息
     * @param session webSocket的会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            this.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("连接异常...");
        logger.error("[error=>]",error);

    }

    @OnClose
    public void onClose() {
        String msg = "会诊编号+ "+this.inquiryId+"用户id "+this.userId;
        System.out.println("连接关闭=> "+msg);
        logger.warn(msg);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {

        ConcurrentHashMap<String,Session> map = allVideoMediaPool.get(inquiryId);
        Enumeration<String> keys = map.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            if (key.equals(this.userId)) {
                System.err.println("my id " + key);
                continue;
            }
            if (map.get(key) == null) {
                map.remove(key);
                System.err.println(key + " : null");
                continue;
            }
            Session sessionValue = map.get(key);
            if (sessionValue.isOpen()) {
                System.out.println("发消息给: " + key + " ,message: " + message);
                sessionValue.getBasicRemote().sendText(message);
            } else {
                System.err.println(key + ": not open");
                sessionValue.close();
                map.remove(key);
            }
        }
    }

    public synchronized void initWebSocket() {
        ConcurrentHashMap<String,Session> webSocketMap;
        if(!allVideoMediaPool.containsKey(this.inquiryId)){
            webSocketMap = new ConcurrentHashMap<>();
        } else
            webSocketMap = allVideoMediaPool.get(inquiryId);

        webSocketMap.put(userId, session);
        allVideoMediaPool.put(inquiryId,webSocketMap);
        System.out.println(userId + " - 连接建立成功...");
        System.out.println(inquiryId + "-会诊编号");
    }

}
